package cn.org.timespace.ons.dao.base.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;

import cn.org.timespace.easyframe.model.permission.EfUser;
import cn.org.timespace.ons.action.base.UserMachineTypeModel;
import cn.org.timespace.ons.dao.TSBaseDAO;
import cn.org.timespace.ons.dao.base.UserMachineTypeDao;
import cn.org.timespace.ons.util.datatime.DateTimeUtils;
import cn.org.timespace.ons.util.pager.Pager;
import cn.org.timespace.ons.vo.base.AppleServer;
import cn.org.timespace.ons.vo.base.Machines;
import cn.org.timespace.ons.vo.base.Options;
import cn.org.timespace.ons.vo.base.UserMachineType;

public class UserMachineTypeDaoImpl extends TSBaseDAO implements
		UserMachineTypeDao {

	@Override
	public void delete(UserMachineType persistentInstance) {
		// TODO Auto-generated method stub
		log.debug("deleting UserMachineType Instance");
		try{
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		}catch(RuntimeException re){
			log.debug("delete fail",re);
			throw re;
		}
	}

	@Override
	public List<Options> findByCode(String code) {
		// TODO Auto-generated method stub
		log.debug("finding all findByCode instances");
	    String hql = "from Options o where code='"+code+"'";
	    return (List<Options>) this.getHibernateTemplate().find(hql);
	}
	//根据用户ID列出信息终端类型
	public List<UserMachineType> findByUserName(String userName) {
		// TODO Auto-generated method stub
		log.debug("finding all findByCode instances");
	    String hql = "from UserMachineType umt where umt.userId='"+userName+"'";
	    return (List<UserMachineType>) this.getHibernateTemplate().find(hql);
	}

	@SuppressWarnings("static-access")
	@Override
	public List<Object> findByCondition(UserMachineTypeModel model, Pager p) {
		// TODO Auto-generated method stub
		log.debug("finding all EfUserLoginLog instances");
		Session session = null;
		Query query = null;
		try{
			StringBuffer queryString = new StringBuffer("select u.theIdMachine,u.userId,u.optionId,u.name,o.name,u.createTime from Options o,UserMachineType u where 1=1 and u.optionId=o.theId");
			
			
			//类型条件
			if(!StringUtils.isEmpty(model.getOptionId())){
				queryString.append(" and u.optionId = '" + model.getOptionId() + "'" );
			}
			
			//名称条件
			if(!StringUtils.isEmpty(model.getName())){
				queryString.append(" and u.name like '%" + model.getName() + "%'" );
			}
			//用户ID
			if(!StringUtils.isEmpty(model.getUserId())){
				queryString.append(" and u.userId = '" + model.getUserId() + "'" );
			}
			
			queryString.append(" order by u.createTime desc");
			session = getSessionFactory().openSession();
			query = session.createQuery(queryString.toString());
			
			
			List<Object> resList = new ArrayList();
			resList.add(query.list().size());
			
			setQueryPager(query, p);
			//resList.add(query.list());
			
			List list = new ArrayList();
			for(int i = 0;i < query.list().size();i++){
				Object[] obj=(Object[])query.list().get(i);
                DateTimeUtils dateTimeUtils=new DateTimeUtils();
                
				UserMachineType userMachineType = new UserMachineType();
				userMachineType.setTheIdMachine(obj[0].toString());
				userMachineType.setUserId(obj[1].toString());
				userMachineType.setOptionId(obj[2].toString());
				userMachineType.setName(obj[3].toString());
				userMachineType.setOptionName(obj[4].toString());
				
				Date dateTimes=dateTimeUtils.parseDate(obj[5].toString(), dateTimeUtils.PATTERN_DATETIME);
				userMachineType.setCreateTime(dateTimes);
				list.add(userMachineType);
			}
			resList.add(list);
			return resList;
		}catch(RuntimeException re){
			log.error("find all failed", re);
			throw re;
		}finally{
			closeSessionAndQuery(session, query);
		}
	}

	@Override
	public List<Object> findByCondition(Pager p) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public UserMachineType findById(String id) {
		// TODO Auto-generated method stub
		log.debug("getting Userapplytype instance with id: " + id);
		try {
			UserMachineType instance = (UserMachineType) getHibernateTemplate().get(
					"cn.org.timespace.ons.vo.base.UserMachineType", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	@Override
	public void save(UserMachineType transientInstance) {
		// TODO Auto-generated method stub
		log.debug("saving UserMachineType instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	@Override
	public void update(UserMachineType instance) {
		// TODO Auto-generated method stub
		try{
			getHibernateTemplate().update(instance);
			
		}catch(RuntimeException re){
			log.error("update failed!",re);
			throw re;
		}
	}

	@Override
	public UserMachineType doCheckOptionsNameIsExist(String userName,String name) {
		
		
		log.debug("UserMachineTypeDaoImpl doCheckOptionsNameIsExist");
		StringBuffer queryString = new StringBuffer("from UserMachineType u where u.userId = '"+userName + "' and u.name = '"+name+"'");
		List<UserMachineType> resList = getHibernateTemplate().find(queryString.toString());
		if(resList != null && resList.size() == 1){
			return resList.get(0);
		}
		return null;
		
	}

	@Override
	public boolean isExistMachineRelation(String id,String userName) {
		// TODO Auto-generated method stub
		log.debug("isExistMachineRelation");
		try{
			
			StringBuffer queryString = new StringBuffer("from TypeAudit m where m.theIdmachine='"+id+"' and m.startUserName='"+userName+"'");
			List<Machines> resList = getHibernateTemplate().find(queryString.toString());
			if(resList !=null && resList.size()>0){
				return false;	//还存在关联，不能删除
			}else{
			return true;	//不存在关联，可以删除
			}
		}catch(RuntimeException re){
			re.printStackTrace();
			throw re;
		}
	}
	
	//列出可选的应用类型
	@Override
	public List<Object> findAppByCondition(UserMachineTypeModel model, Pager p,String nid) {
		// TODO Auto-generated method stub
		log.debug("finding all EfUserLoginLog instances");
		Session session = null;
		Query query = null;
		try{
			StringBuffer queryString = new StringBuffer("select u.theIdMachine,u.userId,u.optionId,u.name,o.name from Options o,UserMachineType u " +
					" where 1=1 and u.optionId=o.theId and u.theIdMachine not in(select ta.theIdmachine from TypeAudit ta where ta.theIdapply='"+nid+"' and  ta.startUserName='"+model.getUserId()+"' and ta.status<>3)");
			
			
			//类型条件
			if(!StringUtils.isEmpty(model.getOptionId())){
				queryString.append(" and u.optionId = '" + model.getOptionId() + "'" );
			}
			
			//名称条件
			if(!StringUtils.isEmpty(model.getName())){
				queryString.append(" and u.name like '%" + model.getName() + "%'" );
			}
			//用户ID
			if(!StringUtils.isEmpty(model.getUserId())){
				queryString.append(" and u.userId = '" + model.getUserId() + "'" );
			}
			
			queryString.append(" order by u.theIdMachine desc");
			session = getSessionFactory().openSession();
			query = session.createQuery(queryString.toString());
			
			
			List<Object> resList = new ArrayList();
			resList.add(query.list().size());
			
			setQueryPager(query, p);
			//resList.add(query.list());
			
			List list = new ArrayList();
			for(int i = 0;i < query.list().size();i++){
				Object[] obj=(Object[])query.list().get(i);
				UserMachineType userMachineType = new UserMachineType();
				userMachineType.setTheIdMachine(obj[0].toString());
				userMachineType.setUserId(obj[1].toString());
				userMachineType.setOptionId(obj[2].toString());
				userMachineType.setName(obj[3].toString());
				userMachineType.setOptionName(obj[4].toString());
				list.add(userMachineType);
			}
			resList.add(list);
			return resList;
		}catch(RuntimeException re){
			log.error("find all failed", re);
			throw re;
		}finally{
			closeSessionAndQuery(session, query);
		}
	}
	
	//根据信息终端ID和应用平台ID判断是否已有添加申请不包括取消的申请
	public boolean findTypeAuditByCondition(String appId,String macId,String userId){
		
		boolean flag = false;
		Session session = null;
		Query query = null;
		try{
			StringBuffer queryString = new StringBuffer("select ta.theIdmachine from TypeAudit ta where ta.theIdapply='"+appId+"' and ta.theIdmachine='"+macId+"' and  ta.startUserName='"+userId+"' and ta.status<>3");
			session = getSessionFactory().openSession();
			query = session.createQuery(queryString.toString());
			if(query.list().size()>0){
				flag = true;
			}
			
		}catch(RuntimeException re){
			log.error("find all failed", re);
			throw re;
		}finally{
			closeSessionAndQuery(session, query);
		}
		return flag;
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isExistByTypeName(String typeName,String userName) {
		boolean flag=false;
		log.debug("finding all findByCode instances");
	    String hql = "from UserMachineType umt where umt.userId='"+userName+"' and umt.name='"+typeName+"'";
	    
	    List<UserMachineType> userMachineType=this.getHibernateTemplate().find(hql);
	    if(userMachineType.size()>0){
	    	flag = true;
	    }
	    return flag;
	}


}
